simply i have a class that has a method to print a specific attibute in a class example:
class Attr:
def __init__(self, name,
wattage):
self.name = name
self.wattage = wattage
def print_attr(self):
print("attribute in class is " + getattr(Attr, wattage)
the expected output is:
attribute name is wattage: test
You don't need a helper function for this, Python does not have restricted access. Simply access the attribute directly:
a = Attr("Name", 10)
print(a.wattage)
If you truly want to make a print method like this, there are two ways to do it:
class Attr:
def __init__(self, name, wattage):
self.name = name
self.wattage = wattage
def print_wattage(self):
print(f'Wattage in *instance* is {getattr(self, "wattage")}') # getattr gets by string name
def print_name(self):
print(f"Name in *instance* is {self.name}")
Related
How to change object printing preview into desirable name ?
class Person:
def __init___(self):
self.name = name
self.age = age
man1 = Person("Jhon",32)
print(man1)
>>> <__main__.Person object at 0x7f9780554b80>
I need to change the preview of object into specifice attribute .(e.g: obj.name , in this example i want the preview will be "Jhon_Person_obj" instead the adress of it)
This code describe the printing reasult i need.
print(Jhon_Person_obj)
print(Jhon_Person_obj.age)
>>> <__main__.Personobject at 0x7f9780554bb0>
>>> 32
Override the __repr__ method of your class:
# PEP8: Class names should normally use the CapWords convention.
class Pokemon():
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Pokemon(name='{self.name}')"
Usage:
p = Pokemon('Pikachu')
print(p)
# Output
Pokemon(name='Pikachu')
As an attribute to a certain class, I'm instantiating a bunch of objects of another class. My problem is that they have ugly names for memory addresses. How do I give them proper names?
class CaseReader(object):
def __init__(self, path):
cases_paths = glob(path + '//*')
cases_names = os.listdir(path)
self.case = [Case(i) for i in cases_paths]
Upon running:
a = CaseReader(path)
a
Out[4]: <__main__.CaseReader at 0x1c6dfc7fa88>
a.case
Out[5]:
[<__main__.Case at 0x1c6dfc99fc8>,
<__main__.Case at 0x1c6dfc99dc8>,
<__main__.Case at 0x1c6dfcaf3c8>,
<__main__.Case at 0x1c6dfcaf448>,
<__main__.Case at 0x1c6dfcaf208>]
Overwrite the __str__ function in the class definition and print what ever attributes you want to see, when you print the reference of the object.
Sample Code
class A:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
I'am using more class based programs, however in some cases it's not handy to provide all self.paramets into a class.
In those cases I want to use a regular input into a function in a class. I figured out a way to achieve both inputs, let me show this in following script:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(a):
if (type(a) == str):
name = a
else:
name = a.name
print("Hello my name is " + name)
p1 = Person("John", 36)
p1.myfunc()
print("---------------------")
Person.myfunc("Harry")
Output:
Hello my name is John
---------------------
Hello my name is Harry
First, the name is initialized by the classes self.params.
Second, the name is provided in the method within the class as a string.
So a type check is necessary.
However I don't think this is a clean approach, because when I have >30 methods I need to implement these type checks again, including upcoming type-error results.
Does anyone know a better approach?
The simplest solution is to implement a __str__ method for your class. This method will be called whenever something tries to convert an instance of the class to a string.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name
p = Person('Jane', 25)
print('Hello', p)
'Hello Jane'
I am using python 3.4 and i am new in object oriented programming and want to access the parent class member in my child class. But it is not accessible. Can anyone help me to get rid of this?
# Base class members can be accessed in
# derived class using base class name.
# Parent or super class
class Company:
def BasicInfo(self):
self.CompanyName = "ABC Solutions"
self.Address = "XYZ"
# Inherited or child class
class Employee(Company):
# constructor
def __init__(self, Name):
print("Employee Name:", Name)
print("Company Name:", self.CompanyName)
def main():
# Create an object
emp01 = Employee("John")
if __name__ == "__main__":
main()
The below mentioned code is working but using the same concept, my code is not working, why? Can anyone explain me the reason.
class Room:
def __init__(self):
self.roomno = 0
self.rcap = 0
self.rooms = {}
self.nog = 10
def addRoom(self):
self.rcap = input("Please enter room capacity:\n")
self.rooms[self.roomno] = self.rcap
class Booking(Room):
def addBooking(self):
while int(self.nog) > int(self.rcap):
print("Guest count exceeds room capacity of: %d" % int(self.rcap))
x = Booking()
x.addRoom()
x.addBooking()
You're missing a call to the superclass' BasicInfo method:
def __init__(self, Name):
print("Employee Name:", Name)
super().BasicInfo()
# ^^Here^^
print("Company Name:", self.CompanyName)
You can replace super().BasicInfo() with a direct reference to the class obviously:
Company.BasicInfo(self)
In your second example, the subclass does not define a __init__ method, so it would inherit that from parent; as a result, the instance variables would be present in the child class.
Your base class method BasicInfo is never getting called. If you call it explicitly either in your child class's __init__, it would work
class Employee(Company):
# constructor
def __init__(self, Name):
super(Employee, self).BasicInfo()
print("Employee Name:", Name)
print("Company Name:", self.CompanyName)
I get a dict to init a class person. there is one field in person: 'name'. 'name' field is optional, meaning that if the dict don't have the 'name' item, then there's no 'name' value of person. I use getter methods to get instance attribute, but it will throw a error if there's no 'name' value. I don't know is there any good programming style to improve my code? Because python create instance field at run time, I don't know how to use getter like java.
class Person:
def __init__(self,person_dict):
try:
self.name = person_dict['name']
except Exception:
pass
def getName(self):
return self.name
pdict = {}
p = Person(pdict)
print p.getName()
AttributeError: Person instance has no attribute 'name'
class Person:
def __init__(self,person_dict):
self.name = person_dict.get('name')
In this case self.name = person_dict.get('name') won't raise Exception and Person objects will have name attribute (None by default)
UPD. Because of getName method is useless, I cut it down from example. Access name attr directly.
class Person:
def __init__(self,person_dict):
self.name = person_dict.get('name', 'default_name')
pdict = {}
p = Person(pdict)
print p.name # there is no need for getter
If you don't want the exception, then you should make sure the instance has a value for name. Since lookup falls back to the class if an attribute can't be found on the instance, an easy way to do this is to simply add name = None (or whatever default value you want the instance to use) to the class definition. Assignment to the attribute on the instance will "hide" the default value.
class Person:
name = None
def __init__(self,person_dict):
try:
self.name = person_dict['name']
except Exception:
pass
You could instead write your __init__ like this:
def __init__(self,person_dict):
self.name = person_dict.get('name')
The get() method of dictionaries returns None if the key isn't found, or you can provide a second argument with a different default value.