简体   繁体   English

在Python中如何将相同的属性从一个类传递到另一个类

[英]In Python how to pass and set the same properties from one class to another

I have a class User with a number of properties. 我有一个具有许多属性的类User I wan to pass 'some' of same properties on the client object and allow them to all be accessed as follows: 我希望在client对象上传递相同属性的“某些”属性,并允许它们按如下方式全部访问:

User(x=1)
User.x
User.y
User.client.x

This is what I have tried, but cannot get it to work. 这是我尝试过的,但是无法正常工作。 TypeError: __init__() takes 1 positional argument but 2 were given. TypeError:__init __()接受1个位置参数,但给出了2个。

class User(object):

    def __init__(self, x, y etc...):

        self.x = x
        self.y = y
        # objects

        self.client = Client(self)

    @property
    def z(self):
        return "test"

class Client(object):

    def __init__(self, **kwargs):

        self.x = kwargs.get('x')

The constructor of client takes 0 positional arguments. 客户端的构造函数采用0个位置参数。 You should add one positional argument for the instance of the User class. 您应该为User类的实例添加一个位置参数。 And you don't really need the **kwargs . 而且您真的不需要**kwargs

class Client(object):

    def __init__(self, parent):

        self.x = parent.x

Also, if you want to access any attribute of user from the client, you can use this. 另外,如果要从客户端访问用户的任何属性,则可以使用此属性。 But imust say, I don't know how this can be useful for you: 但请客气地说,我不知道这对您有什么用:

class User:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.client = Client(self)


class Client:
    def __init__(self, user):
        self.user = user
        self.z = 10
    def __getattr__(self, item):
        __no_attr_marker = object()  # allow a None in a User attribute
        user_item = getattr(self.user, item, __no_attr_marker)
        if user_item is not __no_attr_marker:
            return user_item
        else:
            return self.__getattribute__(item)

testing: 测试:

user = User(1, None)
print(user.x)
print(user.y)
print(user.client.x)
print(user.client.z)
print(user.client.client)

1
None
1
10
<__main__.Client object at 0x7f4e904bf8d0>

this is also a way 这也是一种方法

class User(object):

    def __init__(self, x):
        self.x = x
        self.client = Client(self)


class Client(object):

    def __init__(self, user):
        self.user = user

    @property
    def x(self):
        return self.user.x


u = User(1)
print u.x
u.x = 3
print u.client.x

output 产量

1
3

Your test are using User in a wrong way. 您的测试使用用户的方式有误。 you need to keep the object return by the User class: 您需要通过User类保持对象返回:

user = User(1, 2)
print(user.x)
print(user.y)
print(user.client.x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM