Unable to access the parent class member in base class in python - python

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)

Related

Access parent class method through child instance

I have the following code:
class Organ():
def __init__(self, organ_name, organ_weight):
self.organ_name = organ_name
self.organ_weight = organ_weight
def __repr__(self):
return "The {organ}'s weight is {weight}"\
.format(organ=self.organ_name, weight = self.organ_weight)
class Heart(Organ):
def __init__(self, heart_weight):
self.heart_weight_grams = heart_weight
super().__init__(__class__.__name__, self.heart_weight_grams)
def __repr__(self):
return "My heart's weight is {weight} grams"\
.format(weight=self.heart_weight_grams)
my_heart = Heart(200)
print(my_heart) #returns "My heart's weight is 200 grams"
From my child instance my_heart, how do I access the parent class method __repr__() method?
To access the parent from child use super(), ie : super().__repr__() but here you don't need it, in fact you may not use heart_weight_grams attribut, because it's the same as organ_weight in the parent
If you have more attributs into Heart class, you can call __repr__ parent and concat more info from the child class
class Organ:
def __init__(self, organ_name, organ_weight):
self.organ_name = organ_name
self.organ_weight = organ_weight
def __repr__(self):
return "The {organ}'s weight is {weight}".format(organ=self.organ_name, weight=self.organ_weight)
# return f"The {self.organ_name}'s weight is {self.organ_weight}" # shorter
class Heart(Organ):
def __init__(self, heart_weight, hearbeat=60):
super(Heart, self).__init__("heart", heart_weight)
self.hearbeat = hearbeat
def __repr__(self):
return super().__repr__() + f" and beats at {self.hearbeat}"
my_heart = Heart(200)
print(my_heart) # The Heart's weight is 200
When you inherit a class, you can access parent functions using super. Just use super().__repr__() to access the function.

How to print one Attribute in a class in Python?

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}")

How to access attribute of object from another object's method, which is one of attributes in Python?

I would like to know if it's possible, and if yes, how to access attribute(s) of a "super" class instance, when having composition implemented.
Example provided below is only to provide idea here and setup common ground on further explanations.
I want to have access to "id" attribute for an instance of MiniVan directly from object "door" (type DoorElement).
My Code
class Car:
def __init__(self, _id):
self.id = _id
class CarElement:
def __init__(self, name):
self.name = name
def get_car_id(self):
# Body which will access value of attribute "id"
return car_id
class MiniVan(Car):
def __init__(self, _id):
super(MiniVan, self).__init__(_id)
self.door = DoorElement('door')
self.engine = EngineElement('engine')
class DoorElement(CarElement):
def __init__(self, name):
super(DoorElement, self).__init__(name)
class EngineElement(CarElement):
def __init__(self, name):
super(EngineElement, self).__init__(name)
def main():
mini_van = MiniVan(123)
id_from_door = mini_van.door.get_car_id()
id_from_engine = mini_van.engine.get_car_id()
print(id_from_door) # Expected output 123
print(id_from_engine) # Expected output 123
if __name__ == '__main__':
main()
Expected:
Printed out twice "123"
What I've tried:
Passing required attribute during creating object
I know that I could just define init method with passing "car_id" but for some reasons I would love to avoid it if possible. If not, I would propably just go for it.
to set class attribute, and then call it from CarElement class within classmethod e.g.:
#classmethod
def get_id(cls):
return Car.id
But issue with this solution is that, I can have many child-classes for Car class (MiniVan, Truck, etc.) and I want have it still working.
Trying to use descriptor
def __get__(self, instance, owner):
return instance.id
But I could understand it wrong, and actually getter (as far as I understand clean code) should return instance of a class and not any attribute.
Additional Info
I will ALWAYS use CarElement (or child classes) instances as attributes of instance of Car (or child classes) instances - different usage will be treated as use-error
There can be a lot of different child classes of Car class, but always within inheritance way ( Car <- RacingCar(Car) <- FormulaOneCar(RacingCar) ) but no composition
In order for your code to work, you would have to initialize all CarElement-s with car_id. Currently, the error you are getting comes from lack of such a variable in the scope of the method. My idea of a change is this:
class CarElement:
def __init__(self, name, car_id):
self.name = name
self.car_id = car_id
def get_car_id(self):
# Body which will access value of attribute id
return self.car_id
I can't see any other magic way.

Inheritance from a parent class without arguments

I have two classes. A vehicle class and a car class. My vehicle class does not have any attributes so I can call it without any arguments. Same for my car class. The car class is a sub class for vehicle class.
In my vehicle class I have a variable assigned a string with some text. How can my sub class car inheritance that variable?
Code:
class Vehicle(object):
def __init__(self):
self.__astring = 'Hello'
def get_string(self):
print self.__astring
class Car(Vehicle):
def __init__(self):
Vehicle.__init__(self)
# Here I need to make a working variable
self.__car_string = self.__astring
self.__car_string2 = ' Again'
self.__big_string = self.__car_string + self.__car_string2
# This method should print 'Hello Agan'
def get_car_string(self):
print self.__big_string
string1 = Vehicle()
string1.get_string() # This prints Hello
string2 = Car()
string2.get_car_string() # This should print Hello Again
When I run the code, I get:
AttributeError: 'Car' object has no attribute '_Car__astring'
I do understand why, but I do not know how to inherit that variable with the string.
The correct way to mark an attribute as private (meaning it should not be used directly outside of a method of that class, not that it cannot), is to prefix it with a single underscore.
A getter method should return the value, not print it. If you need to print the value, you can always print the return value of get_string; you cannot (easily) access a value that is directly printed by a method.
class Vehicle(object):
def __init__(self):
self._astring = 'Hello'
def get_a_string(self):
return self._astring
class Car(Vehicle):
def __init__(self):
Vehicle.__init__(self)
# Here I need to make a working variable
self._car_string = self.get_a_string()
self._car_string2 = ' Again'
self._big_string = self._car_string + self._car_string2
def get_car_string(self):
print self._big_string
The language itself will not stop you from accessing Vehicle._astring directly outside of the Vehicle class, but it should be considered a bug to do so.

Accessing instance constructor argument within a method

Just a quick question, so i have a class named animal and when you create the class you can initialise it with a dogName.
class animal:
def __init__(self, dogName):
self._owner = ""
self._address = ""
def setOwnerDetails(self, name, address):
self._owner = name
self._address = address
def getDetails(self):
return self._owner, self._address
def getName(self):
return self.dogName
##Does not work, trying to access constructor argument.
So when you initialise the instance with a value, which is dogName and in this instance the Dogname is Lucy, how can i access this value within a method?
I know i can do this by creating a instance variable but is there any other way i can do it. The variable above understandable does not work but is there any other way?
dog1 = animal("Lucy")
dog1.setOwnerDetails("Thomas", "35 Trop")
result = dog1.getDetails()
print(dog1.getName()) # trying to print the dog Name that is in the constructor argument.
Any help will be appreciated, I might not have explained it well.
You need to set dog_name as an instance attribute in the constructor:
def __init__(self, dog_name):
self._owner = ""
self._address = ""
self.dog_name = dog_name
You will then be able to access the attribute in the methods using self.dog_name.
Aside: as #jonrsharpe mentions in the comments, you should change your variable name from dogName to dog_name for PEP-8 compliance.

Categories

Resources