AttributeError: 'Robot' object has no attribute 'introduce_self' - python

I'm a beginner in class & objects and was wondering why the line r2.introduce_self had an attribute error with an object that doesn't have an attribute.
class Robot:
def __init__(self, rname, rcolor, rweight):
self.name = rname
self.color = rcolor
self.weight = rweight
def introduce_self(self):
print("my name is " + self.name)
r1 = Robot("Tom", "Red", 30)
r2 = Robot("Jerry", "Blue", 40)
r2.introduce_self()
I tried to check if there were any indentation errors but they were all fine, the code is supposed to have an output that says "my name is Jerry". But it still had an attribute error unfortunately

I believe it is because your indentation having issue. introduce_self should be a method for Robot, so it should be having the same indent as __init__ of Robot class.
Try the below code
class Robot:
def __init__(self, rname, rcolor, rweight):
self.name = rname
self.color = rcolor
self.weight = rweight
def introduce_self(self):
print("my name is " + self.name)
r1 = Robot("Tom", "Red", 30)
r2 = Robot("Jerry", "Blue", 40)
r2.introduce_self()

There seems to be a problem with the "init" spelling. not "init" has to __init__ and you have to give some thing to introduce_self because function outside the class. And the code should look like this :
class Robot:
def __init__(self, rname, rcolor, rweight):
self.name = rname
self.color = rcolor
self.weight = rweight
def introduce_self(self):
print("my name is " + self.name)
r1 = Robot("Tom", "Red", 30)
r2 = Robot("Jerry", "Blue", 40)
introduce_self(r2)
>>>my name is Jerry
You can also enclose your function in class and do it:
class Robot:
def __init__(self, rname, rcolor, rweight):
self.name = rname
self.color = rcolor
self.weight = rweight
def introduce_self(self):
print("my name is " + self.name)
r1 = Robot("Tom", "Red", 30)
r2 = Robot("Jerry", "Blue", 40)
r2.introduce_self()
>>>my name is Jerry

Related

Using Builder Pattern, I got AttributeError: 'NoneType' object has no attribute to builder class function

I try to instance my class that made by using builder pattern
class Cat:
def __init__(self,height,weight, color):
self.height = height
self.weight = weight
self.color = color
def print(self):
print("%d %d %s" %(self.height,self.weight,self.color))
class CatBuilder:
def __init__(self):
self.weight = None
self.height = None
self.color = None
def setWeight(self,weight):
self.weight = weight
def setHeight(self,height):
self.height = height
def setColor(self,color):
self.color = color
def build(self):
cat = Cat(self.height,self.weight,self.color)
return cat
then I use below code to run cat1.print()
#error version
cat1 = CatBuilder().setColor("red").setHeight(190).setWeight(80)
cat1.print()
#correct version
cat_builder = CatBuilder()
cat_builder.setColor("red")
cat_builder.setHeight(180)
cat_builder.setWeight(50)
cat2 = cat_builder.build()
cat2.print()
I think both of code is right, but #error version is not working..
How can I fix it??
I got my answer!
I have to append return self code like below:
class Cat:
def __init__(self,height,weight, color):
self.height = height
self.weight = weight
self.color = color
def print(self):
print("%d %d %s" %(self.height,self.weight,self.color))
class CatBuilder:
def __init__(self):
self.weight = None
self.height = None
self.color = None
def setWeight(self,weight):
self.weight = weight
return self
def setHeight(self,height):
self.height = height
return self
def setColor(self,color):
self.color = color
return self
def build(self):
cat = Cat(self.height,self.weight,self.color)
return cat

How do I add arguments to a subclass in Python 3

class Wolf:
def __init__(self, legs):
self.legs = 4
class Dog(Wolf):
def __init__(self, color):
self.color = color
fido = Dog(legs = 4, color = "brown")
This would spute out an error message. How would I do something like that where I add parameters to the subclass that doesn't pertain to the superclass.
Try this:
class Wolf:
def __init__(self, legs):
self.legs = 4
class Dog(Wolf):
def __init__(self, legs, color):
super().__init__(legs)
self.color = color
fido = Dog(legs=4, color="brown")
That's not how inheritance works. When you inherit from another class, the super-class's parameters are not automatically added to the sub-class's parameter list. You must explicitly accept the desired parameters in your sub-class's constructor and pass them on to the super class's constructor:
class Wolf:
def __init__(self, legs):
self.legs = 4
class Dog(Wolf):
def __init__(self, color, legs):
super().__init__(legs)
self.color = color
fido = Dog(legs = 4, color = "brown")
Here's an example from a tutorial which explains inheritance and shows how to do this. You need to call the parent class's init function as in this similar example from this tutorial:
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __str__(self):
return "%s is a %s" % (self.name, self.species)
class Dog(Pet):
def __init__(self, name, chases_cats):
Pet.__init__(self, name, "Dog")
self.chases_cats = chases_cats
def chasesCats(self):
return self.chases_cats
You still have to pass in the legs argument for Dog, and then use super:
class Wolf:
def __init__(self, legs):
self.legs = 4
class Dog(Wolf):
def __init__(self, color, legs):
super().__init__(legs)
self.color = color
fido = Dog(legs = 4, color = "brown")

Python - create inherited class attribute under condition

class WineComponents(object):
def __init__(self, aroma, body, acidity, flavor, color):
self.aroma = aroma
self.body = body
self.acidity = acidity
self.flavor = flavor
self.color = color
which can be instantiated like so:
wine = Color(aroma='80%', body='30%', acidity='35%', flavor='90%', color='Red')
then I want to be able to create specific classes that will inherit WineComponents():
class Color(WineComponents):
def receipe(self):
pass
and also to have its own attributes, under certain conditions, like so:
class Color(WineComponents):
if self.color == 'Red':
region = 'France'
type = 'Bordeaux'
def receipe(self):
pass
calling the attribute with:
print wine.region
but this does not work:
if self.color == 'Red':
NameError: name 'self' is not defined
is there a workaround this?
Here my five pence:
class WineComponents(object):
def __init__(self, aroma, body, acidity, flavor, color):
self.aroma = aroma
self.body = body
self.acidity = acidity
self.flavor = flavor
self.color = color
class Color(WineComponents):
def __init__(self, aroma, body, acidity, flavor, color):
super(Color, self).__init__(aroma, body, acidity, flavor, color)
if self.color == 'Red':
self.region = 'France'
self.type = 'Bordeaux'
def receipe(self):
pass
if __name__ == '__main__':
wine = Color(aroma='80%', body='30%', acidity='35%', flavor='90%',
color='Red')
print (wine.region, wine.type)
You could do this with a property
class Wine(object):
def __init__(self, aroma, body, acidity, flavor, color):
self.aroma = aroma
self.body = body
self.acidity = acidity
self.flavor = flavor
self.color = color
#property
def region(self):
if self.color == 'Red':
return 'France'
else:
raise NotImplementedError('unknown region for this wine')
Which can be called as this:
>>> wine = Wine(aroma='80%', body='30%', acidity='35%', flavor='90%', color='Red')
>>> wine.region
'France'

Python inherit variables from parent class

Sorry if I don't explain it that well but I'll try my best:
So I want to inherit the variables from the Parent class, but I don't want to pass them again when creating an instance of the Child class because I think that is redundant. I just want to use the eye color from the Parent for example. See the example code below for what I mean
This is what works:
class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
class Child(Parent):
def __init__(self, gender, eye_color, length):
super().__init__(eye_color, length)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men", "Blue", 2)
print(x.eye_color, x.length)
print(y.gender, x.length)
This is what I somehow want:
class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
class Child(Parent):
def __init__(self, gender):
super().__init__(eye_color, length)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men")
print(x.length, x.eye_color)
print(y.gender, x.length)
What you ask does not make sense:
class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
class Child(Parent):
def __init__(self, gender):
super().__init__(eye_color, length)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men")
print(x.length, x.eye_color)
print(y.gender, x.length)
In child, the parameters eye_color and length come from nowhere.
rassar example is good if you want to reuse a parent object.
You can also do the following:
class Parent:
# def __init__(self, eye_color=(default value here), length=(default value here)):
def __init__(self, eye_color="", length=0):
self.eye_color = str(eye_color)
self.length = length
OR
class Parent:
def __init__(self, eye_color="", length=0):
self.eye_color = str(eye_color)
self.length = length
class Child(Parent):
def __init__(self, gender, *args, **kwargs):
super().__init__(*args, **kwargs)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men") # Work with first example of Parent
y = Child("Men", eye_color="Blue", length=2) # Work with first
y = Child("Men", "Blue", 2) # Work with second example
print(x.length, x.eye_color)
print(y.gender, y.length)
You could try passing a Parent instance to the Child initializer...That's probably the closest you'll get.
class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
class Child(Parent):
def __init__(self, gender, parent):
super().__init__(parent.eye_color, parent.length)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men", x)
print(x.length, x.eye_color)
print(y.gender, x.length)
Another thing you could do is hold a last_parent variable:
global last_parent
class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
last_parent = self
class Child(Parent):
def __init__(self, gender):
super().__init__(last_parent.eye_color, last_parent.length)
self.gender = str(gender)
x = Parent("Blue", 2)
y = Child("Men")
print(x.length, x.eye_color)
print(y.gender, x.length)

How to add additional attributes to a class?

How would I add additional locationx and locationy variables to the lists while the program is running?
Example of the class:
class Building:
'Common base class for all buildings'
def __init__(self, name, hp, img, locationx, locationy, height, width):
self.name = name
self.hp = hp
self.img = img
self.locationx = locationx
self.locationy = locationy
self.height = height
self.width = width
building_shipyard = Building("Shipyard",500,shipyard,[1000,2500,5000],[1000,2500,5000],300,300)
For instance, after a user places a new building, I might want self.locationx and self.locationy to be updated from [1000,2500,5000] to [1000,2500,5000,7000].
Just access these attributes:
...
def place_building ():
global building_shipyard
...
building_shipyard.locationx = [1000,2500,5000,7000]
# or
building_shipyard.locationx.append(7000)

Categories