Estimasi Waktu Baca: 2 menit

Deskripsi Fungsi

Fungsi vars() mengembalikan atribut __dict__ dari objek yang diberikan (bila objek tersebut memilikinya)

Sintaks dan Parameter

Berikut sintaks dari fungsi vars()


>>> vars(object)

Fungsi vars() menerima satu parameter opsional berupa:

  • object (opsional) – dapat berupa modul, class, instance, atau objek apapun yang memiliki atribut __dict__

Fungsi vars() nantinya akan mengembalikan:

  • atribut __dict__ dari objek yang menjadi argumennya, bila argumennya kosong maka akan bertindak seperti fungsi locals()
  • TypeError, bila objek tidak memiliki atribut dict

Contoh Penerapan

Bagaimana vars() Bekerja


class Tes:
	def __init__(self, x=50, y=100):
		self.x = x
		self.y = y

objek = Tes()
print(vars(objek))

Keluaran:


{'x': 50, 'y': 100}

Fungsi vars() Pada Objek Bawaan Python


>>> vars(list)
mappingproxy({'__repr__': <slot wrapper '__repr__' of 'list' objects>, '__hash__': None, '__getattribute__': <slot wrapper '__getattribute__' of 'list' objects>, '__lt__': <slot wrapper '__lt__' of 'list' objects>, '__le__': <slot wrapper '__le__' of 'list' objects>, '__eq__': <slot wrapper '__eq__' of 'list' objects>, '__ne__': <slot wrapper '__ne__' of 'list' objects>, '__gt__': <slot wrapper '__gt__' of 'list' objects>, '__ge__': <slot wrapper '__ge__' of 'list' objects>, '__iter__': <slot wrapper '__iter__' of 'list' objects>, '__init__': <slot wrapper '__init__' of 'list' objects>, '__len__': <slot wrapper '__len__' of 'list' objects>, '__getitem__': <method '__getitem__' of 'list' objects>, '__setitem__': <slot wrapper '__setitem__' of 'list' objects>, '__delitem__': <slot wrapper '__delitem__' of 'list' objects>, '__add__': <slot wrapper '__add__' of 'list' objects>, '__mul__': <slot wrapper '__mul__' of 'list' objects>, '__rmul__': <slot wrapper '__rmul__' of 'list' objects>, '__contains__': <slot wrapper '__contains__' of 'list' objects>, '__iadd__': <slot wrapper '__iadd__' of 'list' objects>, '__imul__': <slot wrapper '__imul__' of 'list' objects>, '__new__': <built-in method __new__ of type object at 0x9c70e0>, '__reversed__': <method '__reversed__' of 'list' objects>, '__sizeof__': <method '__sizeof__' of 'list' objects>, 'clear': <method 'clear' of 'list' objects>, 'copy': <method 'copy' of 'list' objects>, 'append': <method 'append' of 'list' objects>, 'insert': <method 'insert' of 'list' objects>, 'extend': <method 'extend' of 'list' objects>, 'pop': <method 'pop' of 'list' objects>, 'remove': <method 'remove' of 'list' objects>, 'index': <method 'index' of 'list' objects>, 'count': <method 'count' of 'list' objects>, 'reverse': <method 'reverse' of 'list' objects>, 'sort': <method 'sort' of 'list' objects>, '__doc__': "list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items"})