Python Attributes and Methods
What you will learn
- How an object stores its attributes
getattr,setattr,hasattr,delattrandvars- What a bound method is
- Methods calling methods, and returning
selfto chain calls - The mutable default trap inside
__init__ - Objects that hold other objects
This lesson builds on lesson 13.1: you can already write a class with __init__, attributes and methods. Now we look more closely at how they work, and at the traps.
1. Attributes live in the object
An attribute is a name attached to an object. The ones created with self.name = ... in __init__ are the object's own data, stored in a dictionary called __dict__:
class Student:
def __init__(self, name):
self.name = name
self.grades = []
self.active = True
def add_grade(self, g):
self.grades.append(g)
return self
def average(self):
return sum(self.grades) / len(self.grades) if self.grades else 0.0
def best(self):
return max(self.grades, default=None)
def summary(self):
return f"{self.name}: {len(self.grades)} grades, average {self.average():.1f}"
s = Student("Rina")
s.add_grade(90).add_grade(75).add_grade(82)
print(vars(s))
print(s.summary())
{'name': 'Rina', 'grades': [90, 75, 82], 'active': True}
Rina: 3 grades, average 82.3
vars(obj) gives the same dictionary as obj.__dict__. It shows exactly what the object holds, which is very useful for debugging.
Quick check: where is `s.name` stored?
In the object itself, in its __dict__ dictionary, under the key "name".
2. Reading and changing by name
You usually write s.name and s.name = "Rina". When the attribute name is in a variable (or a string), use the built-in functions:
| Function | Meaning |
|---|---|
getattr(obj, "name") |
read the attribute (an error if missing) |
getattr(obj, "name", default) |
read it, or return default |
setattr(obj, "name", value) |
set it, creating it if needed |
hasattr(obj, "name") |
does it exist? |
delattr(obj, "name") or del obj.name |
remove it |
setattr(s, "city", "Dhaka")
print(getattr(s, "city"), hasattr(s, "city"), getattr(s, "zip", None))
delattr(s, "city")
print(hasattr(s, "city"))
for name in ["name", "active"]:
print(name, getattr(s, name))
Dhaka True None
False
name Rina
active True
A common use is building an object from options:
class Config:
def __init__(self, **options):
for k, v in options.items():
setattr(self, k, v)
cfg = Config(host="localhost", port=8080)
print(cfg.host, cfg.port)
print(vars(cfg))
localhost 8080
{'host': 'localhost', 'port': 8080}
Here the attribute names come from the keyword arguments (lesson 11.4). Use this with care: attributes that appear from nowhere are hard to find when reading the code.
3. Methods are functions that remember their object
When you write s.average, you get a bound method: the function average tied to the object s. Calling it passes s as self automatically:
m = s.average
print(type(m).__name__)
print(m())
print(m.__self__ is s, m.__func__ is Student.average)
method
82.33333333333333
True True
m.__self__is the object it is tied to.m.__func__is the plain function in the class.
The same function reached through the class is unbound: it needs the object as an explicit first argument:
f = Student.average
print(type(f).__name__)
print(f(s))
function
82.33333333333333
s.average() and Student.average(s) are the same call. The first is how you always write it, but understanding the second explains self.
4. Methods calling methods
Inside a method, call other methods of the same object with self.:
class Person:
def __init__(self, first, last):
self.first = first
self.last = last
def full_name(self):
return f"{self.first} {self.last}"
def greet(self, other):
return f"{self.full_name()} greets {other.full_name()}"
p = Person("Rina", "Hoque")
print(p.full_name())
print(p.greet(Person("Sam", "Lee")))
Rina Hoque
Rina Hoque greets Sam Lee
greet uses full_name for both the object itself (self) and for the other one. Writing full_name() without self. would look for a function in the outer scope and fail with a NameError.
Small methods that each do one job and call each other are much easier to read and test than one long method (lesson 11.8).
5. Returning self: fluent chaining
If a method changes the object, it can end with return self. Then calls can be chained in one expression:
class Calc:
def __init__(self, v=0):
self.v = v
def add(self, n):
self.v += n
return self
def mul(self, n):
self.v *= n
return self
def result(self):
return self.v
print(Calc().add(2).mul(5).add(1).result())
11
It reads like a sentence: start at 0, add 2, multiply by 5, add 1. This is called a fluent interface. The first add_grade(90).add_grade(75) of the Student class used it too. (A method that returns self is the exception to the rule that a method which changes things returns None, lesson 7.2.)
6. Default values and the mutable trap
__init__ is a normal function, so the mutable-default trap of lesson 11.9 applies:
class BadDefault:
def __init__(self, items=[]):
self.items = items
x = BadDefault()
y = BadDefault()
x.items.append(1)
print(y.items, x.items is y.items)
[1] True
Both objects share one list. Use None and make a fresh list inside, and copy a list that you were given:
class GoodDefault:
def __init__(self, items=None):
self.items = [] if items is None else list(items)
x = GoodDefault()
y = GoodDefault([5])
x.items.append(1)
print(x.items, y.items)
[1] [5]
list(items) takes a copy, so the object does not secretly share the caller's list (lessons 7.5 and 11.2).
A related trap is a mutable attribute created at class level, shared by every object. Compare:
class Shared:
items = []
def add(self, x):
self.items.append(x)
a = Shared()
b = Shared()
a.add(1)
print(b.items, a.items is b.items)
[1] True
items = [] in the class body is one list for all objects. Create per-object data inside __init__: self.items = []. Lesson 13.3 explains class attributes.
7. Set everything up in init
A method may use an attribute that no one has set yet. This fails at the point of use, which can be far from the cause:
class Late:
def __init__(self):
self.a = 1
def set_b(self):
self.b = 2
def total(self):
return self.a + self.b
l = Late()
l.total()
AttributeError: 'Late' object has no attribute 'b'
After l.set_b(), l.total() would give 3. The lesson: create every attribute in __init__, with a sensible starting value (None, 0, []), so that any method can run at any time.
8. A naming habit: the leading underscore
A name that starts with one underscore, such as _count, tells readers: "this is internal; do not touch it from outside". Python does not enforce this (lesson 13.4 explains how to protect data properly):
class Counter:
def __init__(self):
self._count = 0
def hit(self):
self._count += 1
c = Counter()
c.hit()
print(c._count, list(vars(c)))
1 ['_count']
9. Objects that hold objects
An attribute can be any object, including another object of a class. This is how complex data is modelled:
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
n = Node(1, Node(2, Node(3)))
vals = []
cur = n
while cur:
vals.append(cur.value)
cur = cur.next
print(vals, n.next.next.value)
[1, 2, 3] 3
This is a linked list: each Node holds a value and a reference to the next node (or None at the end). A Student holding a list of Course objects, or a Car holding an Engine, works the same way (lesson 13.9).
Worked example: a shopping cart
An Item knows its price and quantity, and a Cart holds items, adds new ones, and reports the total. Use return self for chaining, and a fresh list per cart.
class Item:
def __init__(self, name, price, qty=1):
self.name = name
self.price = price
self.qty = qty
def total(self):
return self.price * self.qty
class Cart:
def __init__(self, items=None):
self.items = [] if items is None else list(items)
def add(self, name, price, qty=1):
self.items.append(Item(name, price, qty))
return self
def total(self):
return sum(i.total() for i in self.items)
def most_expensive(self):
return max(self.items, key=lambda i: i.total()).name if self.items else None
def report(self):
return [f"{i.name} x{i.qty} = {i.total()}" for i in self.items]
cart = Cart().add("pen", 2.5, 4).add("book", 12).add("bag", 30, 2)
print(cart.total())
print(cart.most_expensive())
print(cart.report())
print(Cart().total(), Cart().most_expensive())
82.0
bag
['pen x4 = 10.0', 'book x1 = 12', 'bag x2 = 60']
0 None
| Design choice | Why |
|---|---|
Item.total |
each item knows its own cost |
Cart.items created in __init__ |
each cart has its own list |
items=None and list(items) |
no mutable default, no shared list |
add returns self |
calls can be chained |
if self.items else None |
an empty cart does not crash max |
A Cart holds Item objects and delegates to them (i.total()). The items and prices are made up.
Common mistakes
- Forgetting
self.when calling another method or using an attribute. - Creating a list or dictionary at class level (shared by every object) instead of in
__init__. - Using a mutable default such as
items=[]in__init__. - Setting an attribute only in some other method, so that methods fail when called in the "wrong" order.
- Making attributes appear from nowhere with
setattr, when plainself.x = ...would be clearer. - Forgetting
return selfand then chaining, which givesNone.method.
Key takeaways
- An object's attributes live in its
__dict__(see it withvars(obj));getattr,setattr,hasattranddelattrwork with names held in variables. obj.methodis a bound method tied toobj;obj.method()is the same asClass.method(obj).- Methods call each other with
self.; ending a changing method withreturn selfallows chaining. - Create all attributes in
__init__, never use mutable defaults, and copy lists that you are given. - A leading underscore marks an attribute as internal; objects can hold other objects.
Practice
1. How can you see all the attributes of an object s?
Show answer
vars(s) (or s.__dict__).
2. Read the attribute whose name is in the variable field, with the default None.
Show answer
getattr(obj, field, None).
3. Why does def full(): return ... used inside another method as full() fail?
Show answer
A method of the same object must be called as self.full(). A bare full() looks for a function of that name outside the class and raises NameError.
4. What goes wrong with class A: items = [] and def add(self, x): self.items.append(x)?
Show answer
The list is created once, at class level, and shared by every object of the class. Create it in __init__ with self.items = [].
5. Make a method double for a Calc class that doubles self.v and allows chaining.
Show answer
def double(self):
self.v *= 2
return self
6. Why should __init__ create every attribute?
Show answer
So that any method can run at any time without finding a missing attribute and raising AttributeError.