Python get object properties

How to get properties of object in python [duplicate]

So you need to look at or equivalently So the properties would be Solution 3: For an object f, this gives the list of members that are properties: Solution 4: As user2357112-supports-monica points out in a comment to a duplicate question, the accepted answer only gets those properties directly defined on the class, missing inherited properties. Example See this link for more examples and information — https://codesachin.wordpress.com/2016/06/09/the-magic-behind-attribute-access-in-python/ Question: I can see first-class member variables using , but I’d like also to see a dictionary of properties, as defined with the @property decorator.

How to get properties of object in python [duplicate]

class ClassB: def __init__(self): self.b = "b" self.__b = "__b" @property def propertyB(self): return "B" 

I know getattr,hasattr. can access the property. But why don’t have the iterattr or listattr ?

Expect result of ClassB object:

Expect result of ClassB class:

Thanks @juanpa.arrivillaga ‘s comment. vars(obj) and vars(obj.__class__) is different!

Читайте также:  Введение в python ответы

Use the built-in vars as follows:

properties = [] for k,v in vars(ClassB).items(): if type(v) is property: properties.append(k) 

Using a list-comprehension:

>>> [k for k,v in vars(ClassB).items() if type(v) is property] ['propertyB'] 

To list propeties of a python Class you can use __dict__

>>> class C(object): x = 4 >>> c = C() >>> c.y = 5 >>> c.__dict__

See this link for more examples and information — https://codesachin.wordpress.com/2016/06/09/the-magic-behind-attribute-access-in-python/

How do I look inside a Python object?, type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively. Share.

Object Oriented Programming in Python Part 4

oops #python #inheritanceCreating Classes and Objects in Python — How to use @property Duration: 6:51

In a Python object, how can I see a list of properties that have been defined with the @property decorator?

I can see first-class member variables using self.__dict__ , but I’d like also to see a dictionary of properties, as defined with the @property decorator. How can I do this?

You could add a function to your class that looks something like this:

def properties(self): class_items = self.__class__.__dict__.iteritems() return dict((k, getattr(self, k)) for k, v in class_items if isinstance(v, property)) 

This looks for any properties in the class and then creates a dictionary with an entry for each property with the current instance’s value.

The properties are part of the class, not the instance. So you need to look at self.__class__.__dict__ or equivalently vars(type(self))

So the properties would be

[k for k, v in vars(type(self)).items() if isinstance(v, property)] 

For an object f, this gives the list of members that are properties:

[n for n in dir(f) if isinstance(getattr(f.__class__, n), property)] 

As user2357112-supports-monica points out in a comment to a duplicate question, the accepted answer only gets those properties directly defined on the class, missing inherited properties. In order to fix this, we also need to walk over the parent classes:

from typing import List def own_properties(cls: type) -> List[str]: return [ key for key, value in cls.__dict__.items() if isinstance(value, property) ] def properties(cls: type) -> List[str]: props = [] for kls in cls.mro(): props += own_properties(kls) return props 
class GrandparentClass: @property def grandparent_prop(self): return "grandparent_prop" class ParentClass(GrandparentClass): @property def parent_prop(self): return "parent" class ChildClass(ParentClass): @property def child_prop(self): return "child" properties(ChildClass) # ['child_prop', 'parent_prop', 'grandparent_prop'] 

If you need to get the properties of an instance, simply pass instance.__class__ to get_properties

Print Object’s Attributes in Python, Print Attributes of an Object in Python Using the dir() Function in Python The built-in dir() function, when called without arguments, returns

Python get Object inside Object property by text

i have an object which hold object Example :

class db_foo_mng db_user = "test" def __init__(self): pass class rdata: db_foo = None def __init__(self): self.db_foo = db_foo_mng() pass 

and i can access it like this with no problem :

i like to access the db_user part with string so it will be like: they don’t work of course

self.rdata.db_foo['db_user'] or self.rdata.db_foo.get('db_user') 

If you have a variable which belongs to an instance of the class, then you can use the __dict__ to access it using the string.

If the variable in question is a class variable (like yours) then you can’t even use the __dict__ to get the attributes.

However the vars() method returns the info in a dict. You can probably make use of that. Store that in db_foo.class_variables and use it later.

>>> vars(rdata_obj.db_foo.__class__)['db_user'] 'test' >>> 

Please see the below code for an example.

user@user-Inspiron:~/code/general$ cat example.py class Contained: class_variable = 'This is a class variable' def __init__(self): self.instance_variable = 'This is an instance variable' class Container: def __init__(self): self.contained_class_instance = Contained() self.contained_class_variables = vars(self.contained_class_instance.__class__) if __name__ == '__main__': container = Container() print(container.contained_class_instance.__dict__['instance_variable']) print(container.contained_class_variables['class_variable']) user@user-Inspiron:~/code/general$ user@user-Inspiron:~/code/general$ user@user-Inspiron:~/code/general$ python example.py This is an instance variable This is a class variable user@user-Inspiron:~/code/general$ user@user-Inspiron:~/code/general$ 

How to display object properties in python, 3 Answers 3 ; 1 · for i in mylist: print «student: %s» % i.student. Or, in python 3 friendly code: for i in mylist: print(«student: %s» % i.

Источник

Python get object properties

Last updated: Feb 22, 2023
Reading time · 3 min

banner

# Table of Contents

# Get all attributes of an Object in Python

Use the dir() function to get all attributes of an object, e.g. print(dir(object)) .

The dir function will return a list of the valid attributes of the provided object.

Copied!
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # 👇️ print(bobby.__dict__) # ------------------------------- attributes = list(bobby.__dict__.keys()) print(attributes) # 👉️ ['first', 'last', 'age'] # ------------------------------- # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'first', 'last'] print(dir(bobby))

The dir function takes an object and returns a list containing the object’s attributes.

If you pass a class to the function, it returns a list of the names of the class’s attributes, and recursively of the attribute of its base classes.

# Pretty print the object’s attributes using pprint()

If you need to pretty print the attributes of the object, use the pprint() method.

Copied!
from pprint import pprint class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # ['__class__', # '__delattr__', # '__dict__', # '__dir__', # '__doc__', # . # ] pprint(dir(bobby))

The pprint.pprint method prints the formatted representation of an object.

# Get each attribute and its value

If you need to get each attribute and its value, use the getattr() function.

Copied!
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) for attribute in dir(bobby): print(attribute, getattr(bobby, attribute))

The getattr function returns the value of the provided attribute of the object.

The function takes the object, the name of the attribute and a default value for when the attribute doesn’t exist on the object as parameters.

# Get an object’s properties and values using __dict__

If you need to get an object’s properties and values, use the __dict__ attribute.

Copied!
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # 👇️ print(bobby.__dict__) # ------------------------------- attributes = list(bobby.__dict__.keys()) print(attributes) # 👉️ ['first', 'last', 'age'] # ------------------------------- values = list(bobby.__dict__.values()) print(values) # 👉️ ['bobby', 'hadz', 30]

You can use the dict.keys() and dict.values() methods if you only need the object’s attribute or values.

# Format the object’s attributes into a string

If you need to format the object’s attributes into a string, use the str.join() method and a formatted string literal.

Copied!
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # 👇️ dict_items([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(bobby.__dict__.items()) result = ', '.join(f'key>=str(value)>' for key, value in bobby.__dict__.items()) print(result) # 👉️ first=bobby, last=hadz, age=30

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Copied!
var1 = 'bobby' var2 = 'hadz' result = f'var1>var2>' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces — .

# Get an object’s attributes using vars()

Alternatively, you can use vars() .

The vars() function returns a dictionary containing the object’s properties and values.

Copied!
class Employee(): def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # 👇️ print(vars(bob)) only_attributes = list(vars(bob).keys()) print(only_attributes) # 👉️ ['id', 'name', 'salary'] only_values = list(vars(bob).values()) print(only_values) # 👉️ [1, 'bobbyhadz', 100]

The vars function takes an object and returns the __dict__ attribute of the given module, class, instance or any other object that has a __dict__ attribute.

The vars() function raises a TypeError if the provided object doesn’t have a __dict__ attribute.

Which approach you pick is a matter of personal preference. I’d use the __dict__ attribute directly to be more explicit.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью