Python Forum
Some questions regarding classes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Some questions regarding classes
#2
(Jul-04-2018, 10:36 PM)Truman Wrote: 1. why in class Pets it is necessary to open an empty list
Can just delete has no function(yet) other than it's a empty list that belong to the class,the output will be same.
You can look at list at bye calling it with class name.
I have 3 dogs.
Tom is 6
Fletcher is 7
Larry is 9
And they're all mammals, of course.

# Call it
>>> Pets.dogs
[]

# The instance attributes has the same name "dogs",but it don't overwrite the class attribute dogs
>>> my_pets.dogs
[<__main__.Bulldog object at 0x03B2AE30>,
 <__main__.RussellTerrier object at 0x03B2AE70>,
 <__main__.Dog object at 0x03B2ADF0>]
>>> 
Quote:2. this line confuses me:
Python Code: (Double-click to select all)
print(f'I have {len(my_pets.dogs)} dogs.')
why my_pets.dogs? I don't see a connection. dogs is attribute of the class Pet. Does dogs represents names in my_dogs list methods?
It just used to count,so in the list there will be 3 new instances.
>>> my_pets.dogs
[<__main__.Bulldog object at 0x03B2AE70>,
 <__main__.RussellTerrier object at 0x03B2ADF0>,
 <__main__.Dog object at 0x03B2AD50>]

>>> len(my_pets.dogs)
3

# In the loop this happens when methods get called 
>>> my_pets.dogs[0].name
'Tom'
>>> my_pets.dogs[0].age
6
Quote:what is dog?
See if output is the same Wink
for dog in my_pets.dogs:
    print(f'{dog.name} is {dog.age}')

# Try
for rubberduck in my_pets.dogs:
    print(f'{rubberduck.name} is {rubberduck.age}')
Reply


Messages In This Thread
Some questions regarding classes - by Truman - Jul-04-2018, 10:36 PM
RE: Some questions regarding classes - by snippsat - Jul-05-2018, 12:32 AM
RE: Some questions regarding classes - by Truman - Jul-05-2018, 10:08 PM
RE: Some questions regarding classes - by snippsat - Jul-06-2018, 09:54 AM
RE: Some questions regarding classes - by Truman - Jul-06-2018, 09:11 PM
RE: Some questions regarding classes - by snippsat - Jul-06-2018, 09:45 PM
RE: Some questions regarding classes - by Truman - Jul-06-2018, 10:00 PM
RE: Some questions regarding classes - by snippsat - Jul-06-2018, 10:14 PM
RE: Some questions regarding classes - by Truman - Jul-07-2018, 11:08 PM
RE: Some questions regarding classes - by Truman - Jul-08-2018, 10:36 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020