how to call class properties in function with Python [duplicate] - python

This question already has answers here:
Python: access class property from string [duplicate]
(4 answers)
Closed 17 days ago.
Here is an example:
I have a student class like this
class student():
def __init__(self, x, y, z):
self.name = x
self.age = y
self.ID = z
and a function to print the corresponding property:
def printer(student, parameter_name):
print(student.parameter_name)
My goal is to print the property I want via the function:
s1 = student('John', '14', '9927')
printer(s1, age)
14
print(s1, name)
John
But, actually, my function raises an error: "AttributeError: 'student' object has no attribute 'parameter_name'"
So, how to fix the error and complete my function?

The error occurs because parameter_name is a string, not a property of the student object. To fix this error, you need to use the getattr function to dynamically access the desired property:
def printer(student, parameter_name):
print(getattr(student, parameter_name))
With this change, the following code should work as expected:
s1 = student('John', '14', '9927')
printer(s1, 'age')
14
print(s1, 'name')
John

Related

Can I control how Classes called? [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
What is the difference between __str__ and __repr__?
(28 answers)
How can I choose a custom string representation for a class itself (not instances of the class)?
(7 answers)
Closed 1 year ago.
I wrote some code and was not sure how to make it work as expected,
class Bee():
def __init__(self, name, identifier):
self.name = name
self.identifier = identifier
bee = Bee(name='Bumble', identifier=1)
print(str(bee))
->> Should Print: 1 Bumble
I thought of creating a function in Class Bee as follows:
def get_hive(self):
return '{} {}'.format(self.identifier, self.name)
However, I am not sure how, when I create an object of class Bee, to assign given attributes instead of address of the memory cell.
My code currently ofc prints smth like: <main.Bee object at 0x000001EA24F49460> instead of the attributes.
If you want str(bee) to return a string as you describe, implement a __str__ method:
class Bee():
def __init__(self, name: str, identifier: int):
self.name = name
self.identifier = identifier
def __str__(self) -> str:
return f"{self.identifier} {self.name}"
bee = Bee('Bumble', 1)
print(bee)
prints:
1 Bumble
Note that print will automatically call str on any parameter that's not already a str, so you can just say print(bee) instead of print(str(bee)).

How to print the values of objects stored in a list [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Print out objects stored in a list
(2 answers)
Closed 1 year ago.
I'm trying to iterate over User objects stored in a python list called myusers then print each. This is what I've done:
class User:
def __init__(self,name,age):
self.name = name
self.age = age
myusers= [User("Fred", "30"), User("Doe", "20")]
for i in range(2):
print(str(myusers[i]))
what I get from the above is the memory location as follows:
<__main__.User object at 0x000001FD807B4250>
<__main__.User object at 0x000001FD807F13A0>
However, I was expecting to get:
User("Fred", "30")
User("Doe", "20")
I've seen this question: https://stackoverflow.com/questions/59115308/print-out-objects-stored-in-a-list but it didn't answer my question since I'm using str in the print function. Can anyone let me know when I'm not getting this value?
As remarked in the comments, you should define a __str__ method, which defines how to represent your object as a string.
class User:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return f'User("{self.name}", "{self.age}")'
myusers= [User("Fred", "30"), User("Doe", "20")]
for i in range(2):
print(myusers[i])

Don't understand this error: name 'person' is not defined [duplicate]

This question already has an answer here:
How to use class name in class scope?
(1 answer)
Closed 3 years ago.
I'm trying to run a class named person. The error is name 'person' is not defined. How can I solve this problem?
class person:
person.count = 0
def __init__(self,gender,location,DOB):
# this is constructor method
self.__gender = gender
self.__location = location
self.__DOB = DOB
# to make the variable inaccessible from out of the class
# we have to prefix it with at least two underscores
print(person.__self)
print(person.__DOB)
person.count += 1
def getname(self):
#this is access method
return person.__self
def getDOB(self):
return person.__DOB
def _del_(self):
print('deleted')
First of all, put the line person.count = 0 inside __init__. Next, change every person to self (unless it's the class definition).

How to print object from within a list [duplicate]

This question already has answers here:
Confused about __str__ on list in Python [duplicate]
(8 answers)
Closed 5 years ago.
I have a simple class I created:
class C:
def __init__(self):
self.a = 1
and I want to print a list of objects from this class using a function I created:
def p(s):
print('hi ', s)
This is how I want to call the printing function p: p([C() for i in range(3)])
Unfortunately, this produces hi [<__main__.C object at 0x000000F92A8B9080>, <__main__.C object at 0x000000F92AB0E898>, <__main__.C object at 0x000000F92AB0E978>].
I thought the problem was due to not implementing __str__ so I changed my class into:
class C:
def __init__(self):
self.a = 1
def __str__(self):
return str(self.a)
but I get the same result :(
What I hoped for was hi [1, 1, 1] or hi 1, 1, 1 or something like that, not the memory location of the objects I created.
I can use
for i in range(3):
p(C())
but I want to pass a list of objects to the p function rather than call it for each of my objects. Is that possible?
Replace __str__ with __repr__:
def __repr__(self):
return str(self.a)

Get the name under which a variable or property is stored [duplicate]

This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 6 years ago.
Is there a way to get the name under which a variable or a property is stored?
Something like:
class X:
def __init__(self):
self.name = __name_under_which_I_m_stored__
jeff = X()
print(jeff.name) # yields 'jeff'
Pretty sure that this is not possible, but you never know... Furthermore, I'm aware that the name could be unspecified (do_something(X())) or ambiguous (jeff=frank=X()).
The Python VM has no way to know the literal name of a name. For objects, you can access the name via __name__ attribute.
If you want to do this, you'll need to implement a mapping of names to values. You can do this with a dict.
class X:
def __init__(self):
self.names = {};
def set(self, name, value):
self.names[name] = value
def get(self, name):
return (name, self.names[value])
jeff = X()
jeff.set("name", "jeff");
print(jeff.get("name")) # yields ("name", "jeff")

Categories

Resources