I'm trying to create a class called B which contains an attribute called news (news being an instance of class A taken at instantiation).
class A has been defined earlier.
However, I'm not sure how to write this in code. I have two attempts below, though I'm not sure if either is correct. Can someone provide some insight?
# Attempt 1:
class B():
def __init__ (self, news):
self.news = A()
# Attempt 2:
class B():
news = A() # news being an instance of class A
def __init__(self, news):
self.news = news
Thank you!
Simple:
class B(object):
def __init__(self):
self.news = A()
You create an instance of A
by calling A()
, which you then assign to your instance variable news
. So now B.news
is an sintance of class A
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.