Python Classes and Objects Attribute error : object has no attribute - python

I am new to python and while learning OOP in python i am getting errors like
AttributeError: 'Dog' object has no attribute 'sound'
for below code
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
return print(f"name is {self.name} and age is {self.age}")
def speak(self, sound):
return print(f"{self.name} says {self.sound}")
tommy = Dog("tommy",10)
tommy.description()
tommy.speak("bow-bow")
Now my other doubt is related to inheritance where i am getting error like:
AttributeError: 'Bulldog' object has no attribute 'speed'
for below code :
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
return print(f"name is {self.name} and age is {self.age}")
class Bulldog(Dog):
def run(self, speed):
return print(f"The speed of dog is {self.speed}")
tommy = Bulldog("tommy",10)
tommy.description()
tommy.run(5)

I believe you need to remove the self. when trying to return the print as these are passed through as parameters and not identified in the object itself.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
return print("name is {self.age} and age is {self.age})
class Bulldog(Dog):
def run(self, speed):
return print(f"The speed of dog is {speed}")
tommy = Bulldog("tommy",10)
tommy.description()
tommy.run(5)
This is the same for both speed and sound, note I also changed some formatting about how the print statement works

Related

Error message: "numpy.ndarray' object has no attribute 'set_volume" Python [duplicate]

I am new to python and while learning OOP in python i am getting errors like
AttributeError: 'Dog' object has no attribute 'sound'
for below code
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
return print(f"name is {self.name} and age is {self.age}")
def speak(self, sound):
return print(f"{self.name} says {self.sound}")
tommy = Dog("tommy",10)
tommy.description()
tommy.speak("bow-bow")
Now my other doubt is related to inheritance where i am getting error like:
AttributeError: 'Bulldog' object has no attribute 'speed'
for below code :
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
return print(f"name is {self.name} and age is {self.age}")
class Bulldog(Dog):
def run(self, speed):
return print(f"The speed of dog is {self.speed}")
tommy = Bulldog("tommy",10)
tommy.description()
tommy.run(5)
I believe you need to remove the self. when trying to return the print as these are passed through as parameters and not identified in the object itself.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def description(self):
return print("name is {self.age} and age is {self.age})
class Bulldog(Dog):
def run(self, speed):
return print(f"The speed of dog is {speed}")
tommy = Bulldog("tommy",10)
tommy.description()
tommy.run(5)
This is the same for both speed and sound, note I also changed some formatting about how the print statement works

How would I print "bark" using python classes in this situation?

How would I print "bark" using python classes.
class pet:
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
class dog(pet):
def __init__(self, name, age):
super().__init__(name, age)
def bark(self):
print("bark")
max = pet("max", 5)
max.dog.bark()
To call the dog class's bark method, you need an instance of dog.
max = dog("max", 5)
max.bark()
Here you go.
class pet:
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
class dog(pet):
def __init__(self, name, age):
super().__init__(name, age)
def bark(self):
print("bark")
my_pet = dog("max",3)
my_pet.bark()

what is wrong with this property decorator (python) [duplicate]

This question already has answers here:
How does the #property decorator work in Python?
(15 answers)
Closed 2 years ago.
I tried adding property decorators to my class but something went wrong.
I got 6 errors!!!
my code:
class person:
def __init__ (self, name, age):
self.name = name
self.age = age
#property
def age(self):
return self.age
#age.setter
def age(self, new_age):
if isinstance(new_age, int):
self.age = new_age
def __str__ (self):
return f"{self.name} is {self.age}"
p1 = person('moe',34)
print(person)
You are using same names and the property then shadows the member. This makes these recursion issue as self.age calls itself again and again in setter.
You need to use different attribute name, like this:
class person:
def __init__ (self, name, age):
self.name = name
self._age = age
#property
def age(self):
return self._age
#age.setter
def age(self, new_age):
if isinstance(new_age, int):
self._age = new_age
def __str__ (self):
return f"{self.name} is {self.age}"
p1 = person('moe',34)
print(p1)
You defined age both as a class method and a class variable. When you refer to self.age, the interpreter has no way of knowing what you meant.
Change the code to this to fix it:
class person:
def __init__ (self, name, age):
self.name = name
self._age = age
#property
def age(self):
return self._age
#age.setter
def age(self, new_age):
if isinstance(new_age, int):
self._age = new_age
def __str__ (self):
# Here you can either use the property or the real variable
return f"{self.name} is {self.age}"
p1 = person('moe',34)
print(person)
There may be two mistakes in your code.
First, methods and attributes shouldn't have the same name age.
You should print the instance p1, if I understand your intention correctly.
Something like this:
class person:
def __init__ (self, name, age):
self.name = name
self._age = age
#property
def age(self):
return self._age
#age.setter
def age(self, new_age):
if isinstance(new_age, int):
self._age = new_age
def __str__ (self):
return f"{self.name} is {self._age}"
p1 = person('moe',34)
print(p1)
You get:
moe is 34

How to call a method when an attribute is written

I want to call a method when an attribute of an object is written. For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def isAdult(self):
print(True if self.age>=21 else False)
If i want to call .isAdult() when an object's age is written a value, how can I achieve this?
I heard of people suggesting to use decorators, but they didn't give more details.
What you want to have is called a setter. You must use new-style classes and extend object to use them:
class Person(object):
def __init__(self, name, age):
self.name = name
self._age = age
def isAdult(self):
print(self.age >= 21)
#property
def age(self):
return self._age
#age.setter
def age(self, value):
self._age = value
self.isAdult()
Then, for example:
p = Person("John Doe", 12)
p.age = 16
p.age = 25
will print
False
True
you can use decorator in class like below.
In below code, isAdultDeco will be call when you create Person object.
class Person:
def isAdultDeco(func):
def foo(self, name, age):
func(self, name, age)
print(True if self.age>=21 else False)
return foo
#isAdultDeco
def __init__(self, name, age):
self.name = name
self.age = age
Person('a',22) # True
Person('a',20) # False

Is there another way to get value from object method into object variable

I made code that goes like this
class Dog():
def breed():
return "rottwiller"
def __init__(self, name, age, breed=breed()):
self.name = name
self.age = age
self.breed = breed
Is there another way to achieve "self.breed" value instead of breed=breed(), but through function method as well.
for example something similar to this( I have tried out this that does not work):
def __init__(self, name, age):
self.name = name
self.age = age
self.breed = breed()
You shouldn't name an attribute and a method the same thing. That being said, my suspicions for why you are asking this question tell me I should point you towards the #property decorator.
class Dog():
def __init__(self, name, age, breed):
self.name = name
self.age = age
self._breed = breed
#property
def breed(self):
return self._breed
This is overkill for your example, but if you have a Dog class and a specific breed, I imagine you are thinking about subclasses and possibly more complicated things than you are doing here. Essentially, the #property decorator will allow you to access breed as an attribute, and will return the value of the call to the function you define under it by the same name.
There are a number of issues with the code posted.
The breed method is overwritten in __init__ method as you set the breed attribute. So the method should be renamed.
The breed method needs to specify the first argument self.
class Dog:
def get_breed(self):
return "rottwiller"
def __init__(self, name, age):
self.name = name
self.age = age
self.breed = self.get_breed()

Categories

Resources