Tomáš Vavřinka - 8 months ago 24

Python Question

I have two classes. When I create an instance in the first one would like to work with its attributes in my second class.

`class Dog(object):`

def __init__(self, number):

self.number_of_tricks = number

class Statistics(object):

def get_number_of_tricks(snelf):

return Dog(Max.number_of_tricks)

Now I create a instance

`>>> Max = Dog(15)`

`>>> stat = Statistics()`

`>>>stat.get_number_of_tricks()`

Answer

Initialize your `Statistics`

with that instance of `Dog`

, then the attributes of that `Dog`

will be accessible from `Statistics`

:

```
class Dog(object):
def __init__(self, number):
self.number_of_tricks = number
class Statistics(object):
def __init__(self, dog_instance):
self.dog = dog_instance
def get_number_of_tricks(self):
return self.dog.number_of_tricks
```

And you can do:

```
>>> from my_module import Dog, Statistics
>>> Max = Dog(15)
>>> stat = Statistics(Max)
>>> stat.get_number_of_tricks()
15
```