Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
class Vehicle:
def __init__(self, brand, model, type):
self.brand = brand
self.model = model
self.type = type
self.gas_tank_size = 14
self.fuel_level = 0
def fuel_up(self):
self.fuel_level = self.gas_tank_size
print('Gas tank is now full.')
def drive(self):
print(f'The {self.model} is now driving.')
I am a beginner for python class structure so it does not give error but it gives nothing. Could you explain please where is the mistake or what is the problem?
Simply declaring a class does not make anything happen - you have to actually invoke that code outside of the class.
For example, try adding this code below the class, with no indentation (so that python doesn't consider it to be part of the class):
# create an instance of the Vehicle class, and assign it to a variable called 'v'
v = Vehicle("someBrand", "someModel", "someType")
# call the fuel_up() and drive() methods, which should print to the console
v.fuel_up()
v.drive()
A class will not output anything by itself. When make a class object, for example by v = Vehicle(brand, model, type), it will run the __init__ function. This function does not return anything in your code.
If you want it to output anything from any of the other functions of the class, you should continue with something like
v = Vehicle(brand, model, type)
v.fuel_up()
Your code will just create a class and function. It won't do anything until you initialize the class
class Vehicle:
def __init__(self, brand, model, type):
self.brand = brand
self.model = model
self.type = type
self.gas_tank_size = 14
self.fuel_level = 0
def fuel_up(self):
self.fuel_level = self.gas_tank_size
print('Gas tank is now full.')
def drive(self):
print(f'The {self.model} is now driving.')
#Initializing the class
vehicle = Vehicle(brand="Mercedes-Benz", model="A-Class", type="Automatic")
vehicle.fuel_up()
vehicle.drive()
Output:
Gas tank is now full.
The A-Class is now driving.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 28 days ago.
Improve this question
I'm learning OOP with python and wanted to write code for an inheritance diagram I found online to practice. This is the diagram:
This is my code:
#parent class that is used to set food and family variables for child classes
class Animal:
def __init__(self,family,food):
self.family = family
self.food = food
def getFamily(self):
return self.family
def setFamily(self,newFamily):
self.family = newFamily
def getFood(self):
return self.food
def setFood(self,newFood):
self.food = newFood
#child class that inherits from Animal class
class Cow(Animal):
def __init__(self,owner, family,food):
self.owner = owner
#use the Animal init function to set the family and food properties
Animal.__init__(self,family,food)
def setOwner(self,newOwner):
self.owner = newOwner
def getOwner(self):
return self.owner
class Lion(Animal):
def __init__(self,family,food):
Animal.__init__(self,family,food)
mooingCow = Cow("Bob", "mammal","grass")
print(Cow.__name__+"'s owner: " + mooingCow.getOwner() + ", family: " + mooingCow.getFamily())
hungryLion = Lion("mammal","humans")
My request is, can anyone comment on the correctness of my solution and help me improve it where I can? Also when I removed the Animal parameter from Cow class definition I expected the code to throw an error as Cow is no longer inheriting from Animal so it should not have access to the properties and methods defined in it, however, the code still executes fine. Please could someone also explain why this is happening to me?
Where I expected the error to happen:
class Cow():
def __init__(self,owner, family,food):
self.owner = owner
#use the Animal init function to set the family and food properties
Animal.__init__(self,family,food) # <--- Where I expected the error to happen
class Animal(object):
def __init__(self,family,food):
self.family = family
self.food = food
def getFamily(self):
return self.family
def setFamily(self,newFamily):
self.family = newFamily
def getFood(self):
return self.food
def setFood(self,newFood):
self.food = newFood
#child class that inherits from Animal class
class Cow(Animal):
def __init__(self,owner, family,food):
self.owner = owner
#use the Animal init function to set the family and food properties
super().__init__(family,food)
def setOwner(self,newOwner):
self.owner = newOwner
def getOwner(self):
return self.owner
class Lion(Animals):
pass
mooingCow = Cow("Bob", "mammal","grass")
print(Cow.__name__+"'s owner: " + mooingCow.getOwner() + ", family: " + mooingCow.getFamily())
hungryLion = Lion("mammal","humans")
You can define class Animals as an object to make it a parent class, and you can remove Animal parameter from the Cow class definition, as python will automatically inherit the parent class.
If the Animal class is defined before the Cow class, and Animal class is defined in the same file, python interpreter bypass the error.
In this case, the interpreter recognizes that Animal class defined earlier in the script and will use it as the parent class for the Cow class. However, this is not considered a good practice as it can lead to unexpected behavior if the order of the classes is changed in the script or if the script is imported into another script.
However if you say:
>>> cow = Cow('a', 'b', 'c')
>>> cow.getFamily()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Cow' object has no attribute 'getFamily'
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 11 months ago.
Improve this question
I am learning to write Object-Oriented Programming in Python and practised the following code. Not sure but I feel that I am writing repetitive code in the inheritance section. Would it be possible to write this code in a better way?
class Dog():
species = "Canis familiaris"
#defining object attributes
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old"
#INHERITENCE - creating child classes for Breeds
class jackrusselterrier(Dog):
def speak(self,sound="Arf"):
return f"{self.name} says {sound}"
class Dachshund(Dog):
def speak(self,sound="Woof"):
return f"{self.name} says {sound}"
class BullDog(Dog):
def speak(self,sound="Grr"):
return f"{self.name} says {sound}"
#instantiation of object
miles = jackrusselterrier("miles",4)
buddy = Dachshund("buddy",9)
jack = BullDog("Jack",3)
jim = BullDog("Jim",5)
#displaying result
print(miles)
print(miles.speak())
print(type(miles))
print(isinstance(miles,BullDog))
"Better" is a qualitative term, but if you want to repeat less code, there are several ways you could leverage inheritance further to do so (to some extent).
One idea is to make the speak() method in each child class call a shared method from the parent class, _speak(). This has the advantage of better representing that all three child objects have similar underlying behavior.
class Dog():
species = "Canis familiaris"
#defining object attributes
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old"
def _speak(self,sound):
return f"{self.name} says {sound}"
#INHERITENCE - creating child classes for Breeds
class jackrusselterrier(Dog):
def speak(self,sound="Arf"):
return self._speak(sound)
class Dachshund(Dog):
def speak(self,sound="Woof"):
return self._speak(sound)
class BullDog(Dog):
def speak(self,sound="Grr"):
return self._speak(sound)
#instantiation of object
miles = jackrusselterrier("miles",4)
buddy = Dachshund("buddy",9)
jack = BullDog("Jack",3)
jim = BullDog("Jim",5)
#displaying result
print(miles)
print(miles.speak())
print(type(miles))
print(isinstance(miles,BullDog))
print(buddy.speak())
print(jack.speak())
print(jim.speak())
But each child class still has a method that does pretty much the same thing (calling the parent class), and only differ on their default sound. We could instead only have one speak method, and make this default sound for each class a variable we create when we create the child class. Note however this adds some complexity, as if we make a __init__() method for the child class, we have to call the parent's __init__() method too, and that is a little messy in python.
class Dog():
species = "Canis familiaris"
#defining object attributes
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old"
def speak(self,sound=None):
if sound is None:
sound = self.default_sound
return f"{self.name} says {sound}"
#INHERITENCE - creating child classes for Breeds
class jackrusselterrier(Dog):
def __init__(self,name,age):
self.default_sound = "Arf"
super(jackrusselterrier,self).__init__(name,age)
class Dachshund(Dog):
def __init__(self,name,age):
self.default_sound = "Woof"
super(Dachshund,self).__init__(name,age)
class BullDog(Dog):
def __init__(self,name,age):
self.default_sound = "Grr"
super(BullDog,self).__init__(name,age)
#instantiation of object
miles = jackrusselterrier("miles",4)
buddy = Dachshund("buddy",9)
jack = BullDog("Jack",3)
jim = BullDog("Jim",5)
#displaying result
print(miles)
print(miles.speak())
print(type(miles))
print(isinstance(miles,BullDog))
print(buddy.speak())
print(jack.speak())
print(jim.speak())
Both these options aren't much less repetitive, but they both have the advantage of communicating in different ways that each child class inherits it's speaking behavior from the parent. Which way you do it I think would come down to your preferred style.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am still trying to understand how I can create an instance attribute on Employment_status to store one of the two constant attributes such as RESIGNED or CURRENT_EMPLOYEE.
So, when I defined my two constant class attributes, I can make my constructor to look like Employee(Employment_status, name, surname, number). The employment_status would take the argument from the Employment Status to change either "RESIGNED" or "CURRENT_EMPLOYEE", when the code is executed.
I have tried to performed my own coding, and would like to know if I am on the right track.
class Person:
def __init__(self, name, surname, number):
self.name = name
self.surname = surname
self.number = number
class Employee(Person):
#class attribute
def employment_status(object):
employment_status = "CURRENT_EMPLOYEE"
employment_status = "RESIGNED"
#instance attributes
def __init__(self, name, surname, number,employment_status):
super().__init__(self,name,surname,number)
self._employment_status = employment_status
__init__ looks OK, assuming an Employee simply adds an employment status to a Person.
It looks like it lays the ground work for employment_status to be a property, though, rather than an ordinary method.
#property
def employment_status(self):
return self._employment_status
#employment_status.setter
def employment_status(self, status):
if status not in ["CURRENT_EMPLOYEE", "RESIGNED"]:
raise ValueError("Invalid status: {}".format(status))
self._employment_status = status
Then you can get an employee's status:
>>> e = Employee("bob", "smith", 1, "CURRENT_EMPLOYEE")
>>> e.employment_status
"CURRENT_EMPLOYEE"
or change it
>>> e.employment_status = "RESIGNED"
>>> e.employment_status
"RESIGNED"
>>> e.employment_status = "foo" # raises an exception
>>> e.employement_status
"RESIGNED" # unchanged
Note that __init__ should use the setter as well, instead of assigning directly to _employment_status:
def __init__(self, name, surname, number,employment_status):
super().__init__(self, name, surname, number)
# not self._employment_status = ...
self.employment_status = employment_status
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
My question shows the problem pretty well, so I will go straight to the code.
class Boxer:
def __init__(self, name):
self.name = name
self.health = 100
self.damage = 20
self.power = 30
here is the original or parent class
class Prince(Boxer):
self.damage = 40
self.health = 80
What I am trying to do is inherit most of the class attributes, and only edit these 2 (damage, health), is there any way to do this without having to create a whole other class?
Ok so two things are not quite right here. First off, the code for Prince - self can only be used inside methods, like the constructor. The attributes for Prince should actually look like:
class Prince(Boxer):
damage = 40
health = 80
Second, the constructor in Boxer is going to overwrite those default values when it is called. So, for those to be overrideable, you need to set the attributes in the class definition, not the constructor:
class Boxer:
health = 100
damage = 20
power = 30
def __init__(self, name):
self.name = name
That should get you somewhere to working as you intended.
EDIT
If you really don't want to use a subclass for every type of boxer, an alternative could be to use default values in your constructor, and these can be overridden. So:
class Boxer:
def __init__(self, name, health=100, damage=20, power=30):
self.name = name
self.health = health
self.damage = damage
self.power = power
Then:
Boxer("Alan") # Ordinary boxer
Boxer("Prince", damage=40, health=80) # Prince is special
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have the following problem. I have a list of elements of Person type. They have inside them some int members which are constantly changing. When such change occurs, I want to invoke another method. Does anyone can propose some solution to my problem how to invoke the method just after the member is changed?
class Person:
def __init__(self):
self.age = 20
class Controller:
p1 = Person()
p2 = Person()
personList = [p1,p2]
def hb:
print("happy birthday")
And I want to invoke hb method when the age of person is changed. The following code is just an example to show the matter.
Use a getter and setter decorator:
class MyClass:
def __init__(self):
self.init = True
self.attribute = 1
self.init = False
#property
def attribute(self):
# Do something if you want
return self._attribute
#attribute.setter
def attribute(self, value):
if not self.init:
print('Value of "attribute" changed:', value)
self._attribute = value
testobject = MyClass()
testobject.attribute = 2
I have added an additional init-variable to prevent the changed-code being called in init phase.