reusing a variable defined in a python class - python

Let's say I define a class. I have a fun method, where I create self.x. I want to use self.x in a different method (reuse). How could I do that? Because I tried what I wrote and didn't work. Thanks!
class test:
def __init__(self,t):
self.t = t
def fun(self):
self.x = self.t+1
def reuse(self):
self.y = self.x

You need to create all the variables in the __init__ method.
Try this:
class test:
def __init__(self,t):
self.t = t
self.x = 0
self.y = 0
def fun(self):
self.x = self.t+1
def reuse(self):
self.y = self.x

Related

How to access the stored array in class

I want to access the array i have filled throughout the for loop,however what i get it is still empty array when call fill_particles().particles, is there any way to get rid of this problem? here is my code.
class particle(object):
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
class fill_particles():
def __init__(self):
self.particles=[]
def fill(self):
for i in range(5):
self.particles.append(particle(i,i+1,i+2))
You need to instantiate the class and call fill(). Here's a working example, along with extra functions for display purposes:
class Particle(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return f'Particle(x={self.x}, y={self.y}, z={self.z})'
class Particles:
def __init__(self):
self.particles = []
def fill(self):
for i in range(5):
self.particles.append(Particle(i, i + 1, i + 2))
def __repr__(self):
return f'Particles({self.particles!r})'
particles = Particles()
print(particles)
particles.fill()
print(particles)
Output:
Particles([])
Particles([Particle(x=0, y=1, z=2), Particle(x=1, y=2, z=3), Particle(x=2, y=3, z=4), Particle(x=3, y=4, z=5), Particle(x=4, y=5, z=6)])

How to initialize one parent at a time in multiple inheritance?

Suppose I have the following class inheriting from classes A and B:
class A:
def __init__(self):
self.x = 2
class B:
def __init__(self,u):
self.y = u + 2
class C(A,B):
def __init__(self):
#self.y should be 4 here
How do I initialize B only after initializing A? Using super(C,self).__init__() doesn't let me use attributes of A into B.
You don't HAVE to use super.
class A:
def __init__(self):
self.x = 2
class B:
def __init__(self,u):
self.y = u + 2
class C(A,B):
def __init__(self):
A.__init__(self)
B.__init__(self, self.x)
Now, that does mean some pretty tight coupling, in that C has to be way too aware of what A.__init__ does.
Just do this:
class A:
def __init__(self):
print("A was initialized")
self.x = 2
def getX(self):
return self.x
class B:
def __init__(self, u):
print("B was initialized")
self.u = u +2
class C(A,B):
def __init__(self, **kw):
A.__init__(self)
B.__init__(self, self.getX())
Alternatively, with super:
class A:
def __init__(self):
self.x = 2
class B:
def __init__(self,u):
self.y = u + 2
class C(A,B):
def __init__(self):
super().__init__()
super(A, self).__init__(self.x)
If you want to pass attributes in between classes use something like a return statement. Then in your B class use whatever the A class returned.

Unresolved attribute reference '...' for class '...'

When I call the render() method in the Zombie class, I want to add an instance of the Zombie object into ZombieList.list. When I try to do this, it says
Unresolved attribute reference list for class ZombieList.
Should I try to do this another way?
class ZombieList:
def __init__(self):
self.list = []
for zombie in self.list:
ds.blit(zombie.image, (1000, random.randint(10, 790)))
class Zombie(object):
def __init__(self):
self.attack = 3
self.speed = 5
self.health = 30
self.image = pygame.image.load("Assets/green zombie.png")
self.zombieList = []
def render(self):
ZombieList.list.append(self)
You've to create a ZombieList object, where you can append the Zombie objects to.
You can add a Class Objects to to the class Zombie:
class Zombie(object):
zombies = ZombieList()
def __init__(self):
self.attack = 3
self.speed = 5
self.health = 30
self.image = pygame.image.load("Assets/green zombie.png")
def render(self):
Zombie.zombies.list.append(self)
You cannot append to a list of a class. You need to append to an instance of a class. For instance:
class ZombieList:
def __init__(self):
self.list = []
for zombie in self.list:
ds.blit(zombie.image, (1000, random.randint(10, 790)))
my_zombie_list = ZombieList() # create an instance
class Zombie(object):
def __init__(self):
self.attack = 3
self.speed = 5
self.health = 30
self.image = pygame.image.load("Assets/green zombie.png")
self.zombieList = []
def render(self):
my_zombie_list.list.append(self) # refer to the previously created instance
There is no attribute list in ZombieList. Only once you've created a ZombieList through e.g. self.zombie_list = ZombieList() will you be able to make use of your list through self.zombie_list.list.
Even then, though, I imagine this probably isn't the design you're aiming for: I imagine that you don't want a ZombieList for each individual Zombie. Rather, whoever is initializing the Zombie objects should probably be in charge of maintaining the ZombieList instance as well.
You will also run into other issues. For example, the loop in
self.list = []
for zombie in self.list:
ds.blit(zombie.image, (1000, random.randint(10, 790)))
will never have any effect since self.list is always empty when that code is executed (since you've defined it to be empty on the previous line).

How should I implement, and what should I call, a common base class for Area and Point?

So I want a Point and an Area classes similar to how C# has Point and Size. Here are simple implementations of the two classes:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
# Many other magic methods too!
class Area:
def __init__(self, width=0, height=0):
self.width = width
self.height = height
def __add__(self, other):
return Area(self.width + other.width, self.height + other.height)
# Many other magic methods too!
As you can see, the two classes are exact duplicates, except one has x, y while the other has width, height.
What would be a good solution for implementing some kind of base class for these two?
If you don't mind using immutable objects, you could subclass tuple to craete a base class for all of the two dimensional stuff:
class _2dTuple(tuple):
def __new__(cls, hor=0, ver=0):
super().__new__(cls, (hor, ver))
def __add__(self, other):
return type(self)(self[0] + other[0], self[1] + other[1])
Now when you subclass your _2dTuple, you can just create property getters for your x, y and width, height:
class Point(_2dTuple):
#property
def x(self):
return self[0]
#property
def y(self):
return self[1]
class Area(_2dTuple):
#property
def width(self):
return self[0]
#property
def height(self):
return self[1]

Python: trying to fix indentation error

class Cylinder(object):
self.pi = 3.14
def __init__(self,height=1,radius=1):
self.height = height
self.radius = radius
def volume(self):
return self.pi * self.radius**2 * self.height
def surface_area(self):
pass
Remove self from the second line. self is used only inside class methods to access class instance. But class attributes declared on class-level apply not to single class instance, but to class itself and all its instances: so they do not require self.

Categories