0
Could someone please explain to me what an "object" is?
It's referred to a lot and I think it usually makes sense in different contexts, but I'm still not 100% sure what's being referred to :)
4 odpowiedzi
+ 2
# It's something that can have attributes and methods, it is a collections of variables, called attributes and functions called me this that are accessible by the name of the class or the istance of the class followed by a point and the name of the attribute and the method.
class Cat:
def __init__(self, name):
self.name = name
self.verse = "miao"
def speak(self):
print ("I am a cat and my name is", self.name)
jim = Cat("Jim")
# here is the attribute
print (jim.verse)
# here is the method
jim.speak()
# also strings are objects with methods like upper()
# >>> output:
# miao
# I am a cat and my name is Jim
So, to create the object jim based on the class Cat you write:
>>> im = Cat("Jim")
Now you got this object that passes it's name to the class to personalize it. Belonging to the class, each object of that class can have access to it's attributes putting the name of the object a dot and the name of the attribute after
>>> jim.name
"Jim"
Cat() has a method too to print his name in a nice way. To access to this you write:
jim.speak()
There is also an attribute that is the same for all the cats that will be constructed with the class Cat and this attribute is the verse. So there is no need to pass an argument when you create a new cat, because all the cat do the same verse, in general.
So, I think that an object is a collection of attributes and methods that you can 'attach' to a new object belonging to that class.
So if can create another cat object:
>>> bill = Cat("Bill")
>>> bill.name
"Bill"
>>> bill.speak()
Ï am a cat and my name is Bill"
>>> bill.verse
"miao"
>>> jim.verse
"miao"
0
@Kendrick Thanks for the reply, but that sounds like a variable you're describing. I'm assuming they would not use the word "object" when talking about variables :/
0
Simple Put, an object is a collection of data and functions that together could logically be used to represent a real world OBJECT. For example, you, personally, have a name, a birthday, an address, a gender, etc... functional programming would just store each of those pieces of data separately as variables. but OOPs object programming) creates an object called Person to group all that data together. Then during the program's run time. an INSTANCE of that object is created called Martin, then populated with your data. Finally one can added Methods, or functions that are specifically associated with that object. For example. Martin.Walk(200 feet) would call a function within the Person object and applies to the martin INSTANCE. hope that helps.
- 2
I believe it's just a container. Ex: word = 'Hallo' word would be an object containing the string Hallo.